<template>
  <a-textarea
    :value="value"
    :placeholder="placeholder"
    style="height: auto"
    :rows="rows"
    @input="inputChange"
  />
  <div class="hv-margin-top10 hv-flex hv-flex-justify-content-between">
    <a-button type="primary" size="small" @click="validateJson(true)">
      验证JSON
    </a-button>
    <a-button type="primary" size="small" @click="formatting"> 格式化 </a-button>
  </div>
</template>

<script lang="ts" setup>
import { notification } from "ant-design-vue";

const props = defineProps({
  value: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "请输入JSON数据...",
  },
  rows: {
    type: Number,
    default: 6,
  },
});

const emit = defineEmits(["update:value", "input"]);

const emitValue = (text: string) => {
  emit("update:value", text);
  emit("input", text);
};

const inputChange = (e: any) => {
  emitValue(e.target.value);
};

const validateJson = (showMsg: boolean) => {
  try {
    const json = JSON.parse(props.value);
    if (showMsg) {
      notification.success({
        message: "提示",
        description: "验证成功!",
      });
      return;
    } else {
      return json;
    }
  } catch (e: any) {
    console.error(e.message);
    notification.error({
      message: "提示",
      description: "JSON验证失败：" + e.message,
    });
    return null;
  }
};

const formatting = () => {
  const json = validateJson(false);
  if (null !== json) {
    const formatTxt = JSON.stringify(json, null, "\t");
    emitValue(formatTxt);
  }
};
</script>

<style lang="less" scoped>
@import "./JsonInput.less";
</style>
